// https://leetcode-cn.com/problems/permutations-ii/submissions/
const permuteUnique = (nums) => {
  const results = [];
  const used = new Array(nums.length);
  nums.sort((a, b) => a - b); // 升序排序

  function dfs(path) {
    if (path.length == nums.length) {
      results.push([...path]);
      return;
    }

    for (let i = 0; i < nums.length; i++) {
      if (used[i]) {
        continue;
      }
      if (i - 1 >= 0 && nums[i - 1] == nums[i] && !used[i - 1]) {
        continue;
      }
      path.push(nums[i]);
      used[i] = true;
      dfs(path);
      path.pop();
      used[i] = false;
    }
  }
  dfs([]);
  return results;
};
